//
//  TTPayOrderDetailViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/16.
//  Copyright © 2019 admin. All rights reserved.
//  订单详情页面来的支付

#import "TTPayOrderDetailViewController.h"
#import "TTGeneralTableViewCell.h"
#import "TTPayOrderModel.h"
#import "TTZFBPayTool.h"
#import "TTZFBPayModel.h"
#import "TTPayOrderDetailSuccessViewController.h"

static NSString *cellID = @"cell";

@interface TTPayOrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, copy) NSString *orderNum;
@property (nonatomic, copy) NSString *totalMoney;
@property (nonatomic, assign) int payType;

@property (nonatomic, strong) NSMutableArray *buttonCellModelArray;
@property (nonatomic, strong) TTPayOrderModel *selectOrderModel;    // 选中的那个

@end

@implementation TTPayOrderDetailViewController

- (instancetype)initWithPayType:(int)payType OrderNum:(NSString *)orderNum totalMoney:(NSString *)totalMoney
{
    self = [super init];
    if (self) {
        self.payType = payType;
        self.orderNum = orderNum;
        self.totalMoney = totalMoney;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"支付订单";
    [self getPaymentInfo];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccessNotify) name:orderDetailShopPaySuccessKey object:nil];
    
}

///支付成功的通知
- (void)paySuccessNotify
{
    TTPayOrderDetailSuccessViewController *successVC = [[TTPayOrderDetailSuccessViewController alloc] init];
    [self.navigationController pushViewController:successVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *array = self.dataArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = self.dataArray[indexPath.section];
    TTGeneralTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = array[indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LLGeneralCellModel *model = self.dataArray[indexPath.section][indexPath.row];
    if ([model isKindOfClass:[LLGeneralArrowCellModel class]]) {
        LLGeneralArrowCellModel *arrowModel = (LLGeneralArrowCellModel *)model;
        if (arrowModel.target && arrowModel.action) {
            [arrowModel.target performSelector:arrowModel.action withObject:arrowModel];
        }
    } else if ([model isKindOfClass:[LLGeneralButtonCellModel class]]) {
        LLGeneralButtonCellModel *btnModel = (LLGeneralButtonCellModel *)model;
        if (btnModel.clickBlock) {
            btnModel.clickBlock(btnModel, btnModel.button);
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10)];
    view.backgroundColor = kSeparatorColor;
    return view;
}

// 获取支付信息
- (void)getPaymentInfo
{
    NSDictionary *dic = @{
        @"param.no" : self.orderNum,
        @"param.orderPrice" : self.totalMoney,
        @"param.callWay" : @1
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getPayInfo_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *dic in responseObject) {
            TTPayOrderModel *model = [TTPayOrderModel modelWithJSON:dic];
            [arr addObject:model];
        }
        [self setupDatasWithPayListArray:arr];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

- (void)setupButtonCellWithModel:(LLGeneralButtonCellModel *)model cellBtn:(UIButton *)button
{
    model.isSelect = YES;
    button.selected = YES;
    
    for (LLGeneralButtonCellModel *cellModel in self.buttonCellModelArray) {
        if (cellModel != model) {
            cellModel.isSelect = NO;
        }
    }
    [self.tableView reloadData];
    
}

- (void)setupDatasWithPayListArray:(NSArray *)payArray
{
    [self.buttonCellModelArray removeAllObjects];
    [self.dataArray removeAllObjects];
    
    NSMutableArray *array1 = [NSMutableArray array];
    [array1 addObject:[LLGeneralCellModel setModelWithImageName:nil title:@"订单金额:" contentAttributedString:[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@", self.totalMoney]]]];
    
    [array1 addObject:[LLGeneralCellModel setModelWithImageName:nil title:@"订单编号:" contentAttributedString:[[NSMutableAttributedString alloc] initWithString:self.orderNum]]];
    
    @weakify(self)
    for (int i = 0; i < payArray.count; i++) {
        TTPayOrderModel *model = payArray[i];
        UIColor *color = model.ServiceMoney.floatValue == 0 ? UIColorHex(FF3C3C) : UIColorHex(999999);
        NSString *title = [NSString stringWithFormat:@"%@(￥%@)", model.PayTypeName, model.PayMoney];
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:model.ServiceMoneyPercentText attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12], NSForegroundColorAttributeName : color}];
        
        BOOL select = (i == 0);
        
        LLGeneralButtonCellModel *cellModel = [LLGeneralButtonCellModel setModelWithImageName:@"zhifubao" title:title contentAttributedString:attr rightNormalImageName:@"shopcart_unsel" rightSelectedImageName:@"shopcartlist_sel" clickBlock:^(LLGeneralButtonCellModel * _Nullable model, UIButton * _Nullable button) {
            @strongify(self)
            NSInteger index = [self.buttonCellModelArray indexOfObject:model];
            self.selectOrderModel = payArray[index];
            [self setupButtonCellWithModel:model cellBtn:button];
        } isSelect:select];
        
        self.selectOrderModel = payArray.firstObject;
        [self.buttonCellModelArray addObject:cellModel];
        
    }
    
    [self.dataArray addObject:array1];
    [self.dataArray addObject:self.buttonCellModelArray];
    
    [self setupFooterView];
    
    [self.tableView reloadData];
    
}

// 支付
- (void)payBtnClick
{
    TTZFBPayModel *model = [[TTZFBPayModel alloc] init];
    model.paymentBusines = @"2";
    model.callWay = @"1";
    model.no = self.orderNum;
    model.type = [NSString stringWithFormat:@"%d", self.payType];
    model.platformUserAccount = [TTLoginSingle sharedSingle].loginModel.Mobile;
    model.platformUserName = [TTLoginSingle sharedSingle].loginModel.Name;
    model.serviceMoney = self.selectOrderModel.ServiceMoney;
    model.serviceMoneyPercent = self.selectOrderModel.ServiceMoneyPercent;
    model.goodsTitle = @"商品订单";
    model.goodsTitleSub = @"APP在线支付商品";
    model.paymentType = @"2";
    model.paymentMethod = @"1";
    model.payAmount = self.selectOrderModel.PayMoney;
    NSDictionary *dic = [model modelToDic];
    
    [TTZFBPayTool createOrderNumberWithParams:dic notifyKey:orderDetailShopPaySuccessKey];
    
}

// 暂不支付
- (void)notPayBtnClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 160)];
    UILabel *label = [UILabel labelWithTitle:@"温馨提示：支付订金的客户优先安排配货" color:UIColorHex(CCCCCC) fontSize:12];
    [footerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(0);
    }];
    
    UIButton *payBtn = [UIButton createButtonWithTitle:@"支付" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor cornerRadius:10 target:self action:@selector(payBtnClick)];
    [footerView addSubview:payBtn];
    [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).mas_offset(40);
        make.centerX.equalTo(footerView);
        make.width.mas_equalTo(250);
        make.height.mas_equalTo(40);
    }];
    
    UIButton *notPayBtn = [UIButton createButtonWithTitle:@"以后再说" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:self action:@selector(notPayBtnClick)];
    notPayBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 15, 6, 15);
    [footerView addSubview:notPayBtn];
    [notPayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(payBtn.mas_bottom).mas_offset(30);
        make.centerX.equalTo(footerView);
    }];
    self.tableView.tableFooterView = footerView;
    
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 50;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _tableView.separatorColor = kSeparatorColor;
        [_tableView registerClass:[TTGeneralTableViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)buttonCellModelArray
{
    if (!_buttonCellModelArray) {
        _buttonCellModelArray = [NSMutableArray array];
    }
    return _buttonCellModelArray;
}


@end
